package com.gao.web.controller;

import com.gao.web.pojo.Message;
import com.gao.web.service.MessageService;
import com.google.gson.Gson;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/findcontent")
public class FindmessageContentServlet extends HttpServlet {

    private MessageService messageService;

    @Override
    public void init() throws ServletException {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        messageService = context.getBean(MessageService.class);
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String content = request.getParameter("content");
        List<Message> messages = messageService.findContent(username, content);
        List<Map<String, Object>> recordList = new ArrayList<>();
        for (Message message : messages) {
            Map<String, Object> recordMap = new HashMap<>();
            recordMap.put("id", message.getId());
            recordMap.put("content", message.getContent());
            recordMap.put("username", message.getUsername());
            recordMap.put("post_date", message.getPost_date());
            // 以此类推，将每个字段名和字段值存入Map
            recordList.add(recordMap);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0); // 设置响应状态码，0 表示成功
        result.put("msg", ""); // 设置响应消息，这里可以不设置
        result.put("count", recordList.size()); // 设置数据总数
        result.put("data", recordList); // 设置数据列表

        //将获取的数据转换为json格式
        Gson gson = new Gson();
        String resultJson = gson.toJson(result);
        Map<String, Object> map = new HashMap<>();
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(resultJson); // 将数据以 JSON 格式返回
    }
}

